package com.example.demo.controller;

import com.example.demo.net.Internet;
import com.example.demo.net.NetCommand;
import com.example.demo.net.NetResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class GatewayController {

    @Autowired
    private Internet internet;

    @ModelAttribute
    public void init(HttpServletRequest request, @PathVariable(value = "bank") String bank) {
        NetCommand netCommand = new NetCommand();
        netCommand.setTarget(bank);
        netCommand.setTargetMethod("execute");
        Object[] args = new Object[1];
        args[0] = request.getParameter("message");
        netCommand.setTargetMethodArgs(args);
        request.setAttribute("netCommand",netCommand);
    }

    @GetMapping(value = "/gateway/execute/{bank}", produces = "application/json;charset=utf-8")
    public NetResponse gateway(HttpServletRequest request, @PathVariable(value = "bank") String bank) {
        NetCommand netCommand = (NetCommand) request.getAttribute("netCommand");
        return internet.invoke(netCommand);
    }
}
